package org.itboys.mongodb.service;

import javax.annotation.Resource;

import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.entity.EntityIdDB;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * long类型ID自增类
 * @author ChenJh
 *
 */
@Service
public class IDGeneratorService {

	@Resource(name="baseMongoDS")
	private MongoDataSource baseMongoDS;

	@Autowired
	public UniqueRandomNumberGenerator uniqRndGenerator;

	private long base;

	public IDGeneratorService() {
		this.base = Long.parseLong("100000", 16);
	}
	
	
	/**
	 * 获取下一个自增主键
	 * @param name
	 * @return
	 */
	public long getNextId(String name){
		Query<EntityIdDB> query = baseMongoDS.createQuery(EntityIdDB.class).field("name").equal(name);
		
		UpdateOperations<EntityIdDB> update = baseMongoDS.createUpdateOperations(EntityIdDB.class).inc("currentId");
		
		EntityIdDB entityId = baseMongoDS.findAndModify(query, update, false, true);
		return entityId.getCurrentId();
	}

	public long genUid() {
		Query<EntityIdDB> q = baseMongoDS.createQuery(EntityIdDB.class).field("name").equal("userId");
		UpdateOperations<EntityIdDB> update = baseMongoDS.createUpdateOperations(EntityIdDB.class).inc("currentId");
		EntityIdDB counter = baseMongoDS.findAndModify(q, update, false, true);
		return getNextId(counter.getCurrentId());
	}

	public long getNextId(long seqId) {
		long multiplier = (seqId - 1) / uniqRndGenerator.getUpperLimit();
		long q = seqId % uniqRndGenerator.getUpperLimit();
		if (q == 0) {
			q = uniqRndGenerator.getUpperLimit();
		}
		long id = uniqRndGenerator.generate(q);

		id = (uniqRndGenerator.getUpperLimit() + 1) * multiplier + id + base;

		return id;
	}
}
